package model.parser;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import model.commands.flow.Script;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

public class ScriptPersistor {
	public Element persistScript(Element parent,Script cmd){
		Element scriptElement = new Element("script");
		NativeObjectsPersistor nativePersistor = new NativeObjectsPersistor();
		nativePersistor.persistString(scriptElement, "name", cmd.getName());
		nativePersistor.persistString(scriptElement, "description", cmd.getDescription());
		CommandsPersistor commandPersistor = new CommandsPersistor();
		Element actionsElement = new Element("actions");
		commandPersistor.persistInnerCommands(cmd, actionsElement);
		scriptElement.addContent(actionsElement);
		if (parent != null) {
			parent.addContent(scriptElement);
		}
		return scriptElement;
	}
	
	public Script loadScript(Element element) {
		Script script = new Script();
		NativeObjectsPersistor nativePersistor = new NativeObjectsPersistor();
		script.setName(nativePersistor.loadString(element.getChild("name")));
		script.setDescription(nativePersistor.loadString(element.getChild("description")));
		CommandsPersistor commandPersistor = new CommandsPersistor();
		commandPersistor.loadInnerCommands(element.getChild("actions"), script);
		return script;
	}
	
	public void saveToFile(File file, Script script) {
		Document doc = new Document();
		doc.setRootElement(persistScript(null,script));
		XMLOutputter outputter = new XMLOutputter();
		try {
			outputter.output(doc, new FileOutputStream(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public Script loadFromFile(File file) {
		// loads the activeObject from file
		SAXBuilder builder = new SAXBuilder();
		Script script = null;
		try {
			Document doc = builder.build(file);
			Element root = doc.getRootElement();
			script = loadScript(root);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return script;
	}
	
	public Script loadFromStream(InputStream inputStream) {
		// loads the activeObject from file
		SAXBuilder builder = new SAXBuilder();
		Script script = null;
		try {
			Document doc = builder.build(inputStream);
			Element root = doc.getRootElement();
			script = loadScript(root);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return script;
	}
}
